package com.shopcart.action;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.common.excel.ExcelExport;
import org.common.excel.ExcelHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo.annotation.LoginFilter;
import com.demo.bean.DataTable;
import com.demo.bean.Ret;
import com.demo.controller.CoreAdminController;
import com.demo.dialet.PaginationSupport;
import com.demo.util.JSONUtils;
import com.demo.validator.AdminLoginValidate;
import com.shopcart.domain.Order;
import com.shopcart.domain.OrderDetail;
import com.shopcart.service.OrderDetailService;
import com.shopcart.service.OrderService;
import com.vsd.daoEx.model.OrderEx;

@Controller
@RequestMapping("order")
@LoginFilter(validateClz=AdminLoginValidate.class)
public class OrderController extends CoreAdminController{
	@Autowired
	private OrderService orderService;
	@Autowired
	private OrderDetailService orderDetailService;
	
	private static HashMap<Integer, String> stateMap = new HashMap<Integer, String>();
	
	static {
		stateMap.put(-1, "已取消");
		stateMap.put(1, "待付款");
		stateMap.put(2, "已付款");
		stateMap.put(3, "已发货");
		stateMap.put(4, "交易完成");
		stateMap.put(5, "已评价");
		stateMap.put(6, "正在退款");
		stateMap.put(7, "退款成功");
		stateMap.put(8, "退款失败");
		stateMap.put(10, "订单异常");
	}
	
	
	@RequestMapping("/list")
	@ResponseBody
	public String storeList(HttpSession session,@RequestParam("draw") Integer draw
			,@RequestParam("start") Integer start,@RequestParam("length") Integer length
			,@RequestParam("search[value]") String search,String storeId,Integer type, String beginTime, String endTime,String areaCode,HttpServletRequest request){
		PaginationSupport.byPage(start/length+1, length);
		String roleCode=getSessionParameter("ROLE_CODE", session);
		if("store".equals(roleCode)) storeId=getSessionParameter("id", session);
		List<OrderEx> list = orderService.selectExList(areaCode,storeId,search,beginTime,endTime,type);
		
		return JSONUtils.serialize(new DataTable(draw+1,PaginationSupport.getContext().getTotalCount(), list));
	}
	
	
	@RequestMapping("/findById")
	@ResponseBody
	public String findById(String id){
		Order s = orderService.findById(id);
		return JSONUtils.serialize(s);
	}
	
	@RequestMapping("/goodsList")
	@ResponseBody
	public String goodsList(String id){
		Collection<OrderDetail> list  = orderDetailService.selectByOrderId(id);
		return JSONUtils.serialize(new DataTable(1,list.size(), list));
	}
	
	@RequestMapping("/edit")
	@ResponseBody
	public String editOrder(Order order, String type,HttpSession session) throws Exception {
		
		if (StringUtils.isNotBlank(type)){
			
			if (type.equals("cancel")){
				order.setState(-1);
			}else if (type.equals("refuse")){
				String refuse = order.getRefuseReason();
				order = orderService.findById(order.getId());
				if(StringUtils.isNotBlank(refuse)){
					order.setRefuseReason(refuse);
				}
				
				order.setBackState(8);
				if (order.getState() != -1 && order.getState() <= 3){
					order.setIsShow(1);
				}
			}else if (type.equals("ok")) {
				order.setShipTime(new Date());
				order.setState(4);
			}else if(type.equals("agreeBack")){
				String storeId = getSessionParameter("id", session);
				orderService.storeAgreeBack(order, storeId);
				return JSONUtils.serialize(new Ret(0));
			}
		}
		
		order.setModifyTime(new Date());
		
		int c = orderService.updateByPrimaryKeySelective(order);
		
		if (c != 0){
			return JSONUtils.serialize(new Ret(0));
		}
		
		return JSONUtils.serialize(new Ret(0));
	}	 
	
	
	@RequestMapping("/exportExcel")
	public void exportExcel(String storeId, String beginTime, String endTime,String areaCode,Integer type, HttpServletResponse response,HttpSession session ) throws Exception {
		if(StringUtils.isBlank(areaCode)) areaCode = getSessionParameter("areaCode", session);
		String roleCode=getSessionParameter("ROLE_CODE", session);
		if("store".equals(roleCode)) storeId=getSessionParameter("id", session);
		PaginationSupport.byPage(1, 10000);
		List<OrderEx> list = orderService.selectExList(areaCode,storeId,null,beginTime,endTime,type);

		for (OrderEx ex : list){
			if (ex.getShipPrice() == null){
				ex.setShipPrice(BigDecimal.ZERO);
			}
			
			if (ex.getCashCoupon() == null){
				ex.setCashCoupon(BigDecimal.ZERO);
			}
			
			if (ex.getTotalPay() == null){
				ex.setTotalPay(BigDecimal.ZERO);
			}
			if(ex.getCouponValue()==null){
				ex.setCouponValue("0");
			}
			if(ex.getFull()==null){
				ex.setFull("0");
			}
			if (ex.getPriceChange() == null){
				ex.setPriceChange(BigDecimal.ZERO);
			}else{
				ex.setTotalPay(ex.getTotalPay().add(ex.getPriceChange()));
			}
			
			if(ex.getBackState()!=1){
				ex.setStateString(stateMap.get(ex.getState()));
			}else{
				ex.setStateString(stateMap.get(ex.getBackState()));
			}
			
			ex.setPayTypeString(ex.getPayType() == 1?"在线付款":"货到付款");
			
		}
		
		List<ExcelHeader> headers = new ArrayList<ExcelHeader>();
		headers.add(new ExcelHeader("code", "订单号"));
		headers.add(new ExcelHeader("stateString", "订单状态"));
		headers.add(new ExcelHeader("payTypeString", "支付方式"));
		headers.add(new ExcelHeader("totalPay", "支付金额"));
		headers.add(new ExcelHeader("wineMoney", "酒水减免"));
		headers.add(new ExcelHeader("storeName", "商家"));
		headers.add(new ExcelHeader("nickName", "用户(昵称)"));
		headers.add(new ExcelHeader("username", "用户(账号)"));
		headers.add(new ExcelHeader("full", "优惠券(使用条件)"));
		headers.add(new ExcelHeader("couponValue", "优惠券(抵扣)"));
		headers.add(new ExcelHeader("priceChange", "价格调整"));
		headers.add(new ExcelHeader("payTime", "支付时间"));
		ExcelExport.createWork(headers, response).createExcel(list);
			
	}
	
	
}
